import { _decorator, Component, RigidBody2D, v2, Vec2, Node, Vec3 } from 'cc';
import { JoyStickManager } from '../joyStick/joyStickManager';
import DataManager from '../runTime/dataManager';
import { DIRECTION_UNUM, ENTITY_STATE_ENUM, PARAMS_NAME_ENUM } from '../enums';
const { ccclass, property } = _decorator;

@ccclass('BallCrtl')
export class BallCrtl extends Component {
    private _speed: number = 20;
    private _body: RigidBody2D = null;
    private _stick: JoyStickManager = null;
    private _offset: Vec2 = v2(0, 0);
    private _camera: Node = null;

    protected onLoad(): void {
        this._body = this.getComponent(RigidBody2D);
        this._stick = DataManager.Instance._joyStick;
        this._camera = DataManager.Instance._camera;
    }

    protected start(): void {
        if (this._camera !== null) this._offset = this._camera.getPosition().subtract(this.node.getPosition()).toVec2();
    }

    protected update(): void {
        // 同步相机位置
        if (this._camera !== null) {
            
            this._camera.x = this.node.x + this._offset.x;
            this._camera.y = this.node.y + this._offset.y;
        }

        if (this._stick._dir.x === 0 && this._stick._dir.y === 0) {
            this._body.linearVelocity = v2(0, 0);
            return;
        }

        const vx: number = this._speed * this._stick._dir.x;
        const vy: number = this._speed * this._stick._dir.y;
        this._body.linearVelocity = v2(vx, vy);

        const r: number = Math.atan2(this._stick._dir.y, this._stick._dir.x);
        let degree: number = r * 180 / Math.PI;

        this.updateDirction(degree);
        // degree = 360 - degree;
        // this.node.angle = degree;
    }

    updateDirction(degree: number): void {
        if (degree >= -90 && degree <= 90) {
            DataManager.Instance._player.direction = DIRECTION_UNUM.RIGHT;
            DataManager.Instance._player.state = ENTITY_STATE_ENUM.TURNRIGHT;
        }
        else {
            DataManager.Instance._player.direction = DIRECTION_UNUM.LEFT;
            DataManager.Instance._player.state = ENTITY_STATE_ENUM.TURNLEFT;
        }
    }
}
